/*
 * p4044.cpp
 *
 *  Created on: 2013-7-24
 *      Author: zy
 */
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 1005;
const int INF = 0x7ffffff;
int dp[maxn][205], p[maxn][55], c[maxn][55], cnt[55];
int tp[maxn][205];
vector<int> son[maxn];
int n, m;
void dfs(int u, int pa)
{
	if (u != 1 && son[u].size() == 1)
	{
		for (int i = 0; i <= m; i++)
			dp[u][i] = tp[u][i];
		return;
	}
	for (int i = 0; i <= m; i++)
		dp[u][i] = INF;
	for (int i = 0; i < son[u].size(); i++)
	{
		int v = son[u][i];
		if (v == pa)
			continue;
		dfs(v, u);
		for (int j = m; j >= 0; j--)
		{
			int tem = 0;
			for (int k = 0; k <= j; k++)
				tem = max(tem, min(dp[v][k], dp[u][j - k]));
			dp[u][j] = tem;
		}

	}
	for (int j = m; j >= 0; j--)
		for (int k = 0; k <= j; k++)
			dp[u][j] = max(dp[u][j], dp[u][j - k] + tp[u][k]);

}
int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%d", &n);
		for (int i = 0; i <= n; i++)
			son[i].clear();
		for (int i = 1; i < n; i++)
		{
			int x, y;
			scanf("%d%d", &x, &y);
			son[x].push_back(y);
			son[y].push_back(x);
		}
		scanf("%d", &m);
		memset(tp, 0, sizeof(tp));
		for (int i = 1; i <= n; i++)
		{
			scanf("%d", &cnt[i]);
			for (int j = 1; j <= cnt[i]; j++)
			{
				scanf("%d%d", &c[i][j], &p[i][j]);
				tp[i][c[i][j]] = max(tp[i][c[i][j]], p[i][j]);
			}
		}
		for (int i = 1; i <= n; ++i)
			for (int j = 1; j <= m; ++j)
				tp[i][j] = max(tp[i][j], tp[i][j - 1]);
		memset(dp, 0, sizeof(dp));
		dfs(1, 0);
		printf("%d\n", dp[1][m]);
	}
	return 0;
}
